<template>
  <div class="user-info">
    <!-- 封面图 -->
    <div class="cover-wrap">
      <div
        class="cover"
        :style="{ backgroundImage: `url(${userInfo.cover || defaultCover})` }"
        @click="handleEditCover"
      >
        <div class="cover-mask"></div>
      </div>

      <!-- 头像和用户名 -->
      <div class="user-base">
        <van-image round width="80" height="80" :src="userInfo.avatar" @click="handleEditAvatar" />
        <input
          ref="avatarInput"
          type="file"
          accept="image/*"
          style="display: none"
          @change="handleAvatarChange"
        />
        <div class="user-detail">
          <div class="username">{{ userInfo.username }}</div>
        </div>
      </div>
      <input
        ref="coverInput"
        type="file"
        accept="image/*"
        style="display: none"
        @change="handleCoverChange"
      />
    </div>

    <!-- 用户信息 -->
    <div class="info-content">
      <div class="user-data">
        <div class="stats">
          <div class="stat-item">
            <div class="count">{{ userInfo.likeCount }}</div>
            <div class="label">获赞</div>
          </div>
          <div class="stat-item" @click="handleStatistics('follow')">
            <div class="count">{{ userInfo.followCount }}</div>
            <div class="label">关注</div>
          </div>
          <div class="stat-item" @click="handleStatistics('fans')">
            <div class="count">{{ userInfo.fansCount }}</div>
            <div class="label">粉丝</div>
          </div>
        </div>
        <div class="edit-btn" v-if="route.params.id">
          <van-button
            :type="isFollow ? 'default' : 'primary'"
            size="small"
            @click="handleFollowClick"
          >
            {{ isFollow ? '已关注' : '关注' }}
          </van-button>
          <van-button type="default" size="small" @click="handleMessage">私信</van-button>
        </div>
        <div class="edit-btn" v-else>
          <van-button type="primary" size="small">编辑资料</van-button>
        </div>
      </div>
      <div class="user-desc">{{ userInfo.description || '点击添加介绍，让大家认识你' }}</div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { showToast } from 'vant'
import { userApi } from '@/api/user'
import { useRouter, useRoute } from 'vue-router'

const router = useRouter()
const route = useRoute()
const props = defineProps({
  userInfo: {
    type: Object,
    required: true,
  },
  isFollow: {
    type: Boolean,
    default: undefined,
  },
})

const emit = defineEmits(['getUserInfo'])

const defaultCover = 'https://example.com/default-cover.jpg'
const coverInput = ref(null)
const avatarInput = ref(null)

// 判断是否为当前登录用户
const isCurrentUser = computed(() => {
  const currentUserId = window.localStorage.getItem('uId')
  return currentUserId === props.userInfo._id
})

// 编辑封面
const handleEditCover = () => {
  if (!isCurrentUser.value) return
  coverInput.value.click()
}

// 封面图片改变
const handleCoverChange = async (event) => {
  const file = event.target.files[0]
  if (!file) return

  // 检查文件类型
  if (!file.type.startsWith('image/')) {
    showToast('请选择图片文件')
    return
  }

  // 检查文件大小（限制为 5MB）
  if (file.size > 5 * 1024 * 1024) {
    showToast('图片大小不能超过 5MB')
    return
  }

  try {
    const formData = new FormData()
    formData.append('cover', file)
    await userApi.updateUserInfo(formData)
    showToast('封面更新成功')
    // 触发父组件刷新用户信息
    emit('update')
  } catch (error) {
    showToast('封面更新失败')
  }
}

// 编辑头像
const handleEditAvatar = () => {
  if (!isCurrentUser.value) return
  avatarInput.value.click()
}

// 头像图片改变
const handleAvatarChange = async (event) => {
  const file = event.target.files[0]
  if (!file) return

  // 检查文件类型
  if (!file.type.startsWith('image/')) {
    showToast('请选择图片文件')
    return
  }

  // 检查文件大小（限制为 2MB）
  if (file.size > 2 * 1024 * 1024) {
    showToast('图片大小不能超过 2MB')
    return
  }

  try {
    const formData = new FormData()
    formData.append('avatar', file)
    await userApi.uploadAvatar(formData)
    showToast('头像更新成功')
    // 触发父组件刷新用户信息
    emit('update')
  } catch (error) {
    showToast('头像更新失败')
  }
}
const handleStatistics = (type) => {
  router.push({
    path: `/user/statistics/${props.userInfo._id}`,
    query: {
      type,
    },
  })
}
// 处理关注点击
const handleFollowClick = async () => {
  if (props.isFollow) {
    // 取消关注
    await userApi.unfollow(props.userInfo._id)
  } else {
    // 关注
    await userApi.follow(props.userInfo._id)
  }
  emit('getUserInfo')
}
// 私信
const handleMessage = () => {
  router.push({
    path: `/chat/detail/${props.userInfo._id}`,
    query: {
      type: 'private',
      name: props.userInfo.username,
    },
  })
}
</script>

<style scoped>
.user-info {
  position: relative;
  background-color: var(--bg-color);
  color: var(--font-color-base);
}

.cover-wrap {
  position: relative;
  width: 100%;
  height: 220px;
  overflow: hidden;
}

.cover {
  width: 100%;
  height: 100%;
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
  filter: brightness(0.9);
}

.cover-mask {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(to bottom, transparent 50%, rgba(0, 0, 0, 0.5));
}

.user-base {
  position: absolute;
  bottom: 16px;
  left: 16px;
  right: 16px;
  display: flex;
  align-items: center;
  z-index: 2;
}

.user-detail {
  margin-left: 16px;
}

.username {
  font-size: 22px;
  font-weight: 600;
  color: #fff;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);
}

.info-content {
  position: relative;
  padding: 16px;
  background-color: var(--bg-color);
  border-radius: 10px 10px 0 0;
  margin-top: -10px;
}

.user-data {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.stats {
  display: flex;
  gap: 20px;
}

.stat-item {
  text-align: center;
}

.stat-item .count {
  font-size: 17px;
  font-weight: 600;
  color: var(--font-color-base);
}

.stat-item .label {
  margin-top: 2px;
  font-size: 12px;
  color: var(--font-color-gray);
}
:deep(.van-button--primary) {
  background: var(--color-primary);
  border: none;
}

:deep(.van-button--default) {
  border-color: var(--border-color);
  color: var(--font-color-gray);
}
.edit-btn {
  display: flex;
  flex-direction: column;
  gap: 10px;
}
.van-button {
  height: 34px;
  padding: 0 20px;
  border: 1px solid var(--border-color);
  font-weight: var(--button-font-weight);
}

.user-desc {
  font-size: 14px;
  color: var(--font-color-gray);
  line-height: 1.4;
}
</style>
